package vcproj2cmake.writer;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;

import vcproj2cmake.Configuration;
import vcproj2cmake.Filter;
import vcproj2cmake.Project;

public class cmakeWriter {


	public String writeConfigurationToString(Project project, Configuration configuration, File rootPath){
		String output = "";
		
		output += "PROJECT(" + project.Name + ")\n";
		
		
		ArrayList<String> sourceGroups = new ArrayList<String>();
		Iterator<Filter> iter = project.filter.iterator();
		while(iter.hasNext()){
			Filter filter = iter.next();
			output += filter.writeCMakeFilter(sourceGroups, rootPath);
		}
		
		output+="\n SET(SOURCES ";
		for (int i = 0; i < sourceGroups.size(); i++){
			output+= " ${" + sourceGroups.get(i)+"}";
		}
		output+=")\n";
//		output += "SET(SOURCES \n";
//		for (int i = 0; i < project.files.size(); i++)
//			output += project.files.get(i) + "\n";
//		output += ")\n";		
		
		output += "SET(the_target \"" + project.Name + "\")\n";
		
		//Include directorys
		output += "INCLUDE_DIRECTORIES ( " + configuration.AdditionalIncludeDirectories + ")\n";
		if (configuration.PreprocessorDefinitions != null){
			String[] tmp = configuration.PreprocessorDefinitions.split(";");
			output += "ADD_DEFINITIONS ( ";
			for (int i = 0; i < tmp.length; i++)
				output+= "-D"+tmp[i]+" ";
			output += ")\n";
		}
		
		output += "LINK_DIRECTORIES ( " + configuration.AdditionalLibraryDirectories + ")\n";	
		
		
		
		if (configuration.ConfigurationType == 1) // Executable
			output += "ADD_EXECUTABLE ( ${the_target} ${SOURCES} )\n";
		else if (configuration.ConfigurationType == 2) //DLL
			output += "ADD_LIBRARY ( ${the_target} SHARED ${SOURCES})\n";
		else if (configuration.ConfigurationType == 4) //Static
			output += "ADD_LIBRARY ( ${the_target} STATIC ${SOURCES})\n";
		else{
			System.err.println("Configuration Type is not supported yet");
			System.exit(1);
		}					
		
		if (configuration.AdditionalDependencies != null){
			String[] tmp = configuration.AdditionalDependencies.split(" ");
			output += "TARGET_LINK_LIBRARIES ( ${the_target} ";
			for (int i = 0; i < tmp.length; i++)
				output += tmp[i].replace(".lib", "")+" ";
			output += ")\n";
		}
		
		if (!project.references.isEmpty()){
			output += "ADD_DEPENDENCIES ( ${the_target} ";
			String deps = "";
			for (int i = 0; i < project.references.size(); i++){
				String name = project.references.get(i).name;
				if (name == null)
					continue;
				if (!deps.contains(name))
					deps += name+" ";
			}
			output += deps+" )\n";
		}
		
		return output;
	}
}
